package com.android.manghe.market.activity;

import static com.pay.paytypelibrary.base.PayUtil.PAY_CODE;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.base.frame.extend.IRefresh;
import com.android.base.frame.view.MVPActivity;
import com.android.base.tools.Glide.GlideHelper;
import com.android.base.tools.ToastUtil;
import com.android.manghe.R;
import com.android.manghe.box.activity.BoxGoodDetailActivity;
import com.android.manghe.box.activity.RuleActivity;
import com.android.manghe.box.activity.UnpackingActivity;
import com.android.manghe.box.activity.UnpackingFiveActivity;
import com.android.manghe.box.activity.UnpackingRealActivity;
import com.android.manghe.box.fragment.OpenBoxFragment;
import com.android.manghe.box.model.BoxModel;
import com.android.manghe.box.model.BoxPrizeModel;
import com.android.manghe.box.model.MessageEvent;
import com.android.manghe.box.model.OpenBoxWayModel;
import com.android.manghe.box.model.PayWayModel;
import com.android.manghe.cache.UserHolder;
import com.android.manghe.common.model.BuyMemberShangMengZhiFuRes;
import com.android.manghe.common.model.PaymentTypeRes;
import com.android.manghe.common.webview.ERefreshWebType;
import com.android.manghe.common.webview.SimpleWebViewActivity;
import com.android.manghe.common.webview.WebViewActivity;
import com.android.manghe.common.webview.WebViewParameter;
import com.android.manghe.config.Config;
import com.android.manghe.config.ConstantsUrl;
import com.android.manghe.config.events.RefreshMemberInfoEvent;
import com.android.manghe.market.adapter.BoxAllAdapter;
import com.android.manghe.market.adapter.BoxHistoryAdapter;
import com.android.manghe.market.model.BoxCheckOrderModel;
import com.android.manghe.market.model.BoxSubmitModel;
import com.android.manghe.market.presenter.PBoxDetail;
import com.android.manghe.market.view.ConfirmPayResultDialog;
import com.android.manghe.mine.model.SandPayH5Model;
import com.android.manghe.mine.model.SandPayModel;
import com.android.manghe.quickpay.activity.QuickPayDetailActivity;
import com.android.manghe.user.activity.LoginActivity;
import com.android.manghe.utils.WindowUtils;
import com.android.manghe.view.BoxGiftsUpView;
import com.android.manghe.view.popWindow.BoxGoodsPopWindow;
import com.android.manghe.view.popWindow.OrderSurePopWindow;
import com.android.manghe.view.popWindow.ShowBoxOpenPopWindow;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eightbitlab.rxbus.Bus;
import com.pay.paytypelibrary.base.OrderInfo;
import com.pay.paytypelibrary.base.PayUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.unionpay.UPPayAssistEx;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * author : liuwen
 * e-mail : liuwen370494581@163.com
 * time   : 2021/10/25 15:20
 * desc   :  盒子详情页面
 */
public class BoxDetailActivity extends MVPActivity<PBoxDetail> implements IRefresh {


    public static final int UNION_CODE = 10;
    //对接杉德支付
    private RecyclerView mBoxAllRecyclerView, mBoxHistoryRecyclerView;
    private BoxAllAdapter mBoxAllAdapter;
    private BoxHistoryAdapter mBoxHistoryAdapter;
    private TextView mTvRule, mTvOpenBox;
    private TextView mTvCoin, mtvName;
    private BoxGiftsUpView mBoxGiftsUpView;
    private ImageView mImgSrc;
    private BoxModel.DataBean mCurrentListBean;
    private List<BoxModel.DataBean.GoodsListBean> goods_list = new ArrayList<>();
    private List<PaymentTypeRes.DataBean.PaymentBean> paymentList = new ArrayList<>();


    //支付所需要的参数
    private int mNum = 0;
    private BoxSubmitModel.DataBean mBoxSubmitModel;


    @Override
    public int getLayoutId() {
        return R.layout.activity_box_detail;
    }

    @Override
    protected void initData(@Nullable Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        getTitleBar().setToolbar("盲盒详情").setLeftIcon(R.mipmap.icon_back_black).hideBottomLine().
                setBackgroundColor(ContextCompat.getColor(this, R.color.white));
        mBoxAllRecyclerView = findViewById(R.id.id_all_recycler_view);
        mBoxHistoryRecyclerView = findViewById(R.id.id_box_history_recycler_view);
        mTvRule = findViewById(R.id.id_tv_rule);
        mTvOpenBox = findViewById(R.id.id_open_box);
        mTvCoin = findViewById(R.id.id_tv_coin);
        mtvName = findViewById(R.id.id_tv_name);
        mImgSrc = findViewById(R.id.id_img_src);
        mBoxGiftsUpView = findViewById(R.id.boxGiftsUpView);

        initRecyclerView();
        setListener();

        mCurrentListBean = (BoxModel.DataBean) getIntent().getSerializableExtra("BoxListModel");
        try {
            if (mCurrentListBean != null) {
                if (mCurrentListBean.prices != null && mCurrentListBean.prices._$1 != null) {
                    mTvCoin.setText("￥" + mCurrentListBean.prices._$1.sell_price);
                }
                mtvName.setText(mCurrentListBean.name);
                goods_list = mCurrentListBean.goods_list;
                updateBoxChildGoods(mCurrentListBean.goods_list);
                GlideHelper.loadWithHolderErr(mContext, mCurrentListBean.cover_pic, mImgSrc);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        showLoadingDialog();
        getP().setManghe_id(mCurrentListBean.id);
        getP().getBoxPrizeList(true);
        getP().getBoxPrize();
    }


    private void initRecyclerView() {

        LinearLayoutManager boxAllLinearLayoutManager = new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false);
        LinearLayoutManager boxHistoryLinearLayoutManager = new LinearLayoutManager(this);

        mBoxAllRecyclerView.setLayoutManager(boxAllLinearLayoutManager);
        mBoxHistoryRecyclerView.setLayoutManager(boxHistoryLinearLayoutManager);

        mBoxAllAdapter = new BoxAllAdapter(this, new ArrayList<>());
        mBoxHistoryAdapter = new BoxHistoryAdapter(this, R.layout.item_box_history, new ArrayList<>());
        mBoxAllRecyclerView.setAdapter(mBoxAllAdapter);
        mBoxHistoryRecyclerView.setAdapter(mBoxHistoryAdapter);
    }


    /**
     * 修改上升的开奖名单
     * @param list
     */
    public void updatePrize(List<BoxPrizeModel.DataBean.ListBean> list) {
        mBoxGiftsUpView.setDrawableList(list)
                .setAnimationDelay(3000)
                .setRiseDuration(4 * 1000)
                .setMinHeartNum(2)
                 .setMaxHeartNum(2)
                .setScaleAnimation(1, 0.5f);
        mBoxGiftsUpView.startAnimation(1000000000);
    }

    /**
     * 修改子商品
     *
     * @param goods_list
     */
    private void updateBoxChildGoods(List<BoxModel.DataBean.GoodsListBean> goods_list) {
        mBoxAllAdapter.update(goods_list);

    }

    /**
     * 更新支付方式
     *
     * @param payment
     */
    public void updatePayments(List<PaymentTypeRes.DataBean.PaymentBean> payment,
                               BoxCheckOrderModel.DataBean dateBean, View v) {
        this.paymentList = payment;
        OrderSurePopWindow popWindow = new OrderSurePopWindow(BoxDetailActivity.this,
                mCurrentListBean, dateBean, paymentList);
        popWindow.showPopWindow(v);
        popWindow.setListener(new OrderSurePopWindow.IOrderSureListener() {
            @Override
            public void pay(BoxCheckOrderModel.DataBean model, PaymentTypeRes.DataBean.PaymentBean paymentBean, int use_score) {
                getP().getBoxSubmitOrder(model.manghe_cat_id + "", model.buy_num, paymentBean.pay_id, paymentBean.pay_code,use_score);
            }

        });

    }

    /**
     * 更新订单结果
     *
     * @param dateBean
     * @param v
     */
    public void updateCheckOrder(BoxCheckOrderModel.DataBean dateBean, View v) {
        getP().getPaymentType(dateBean, v);
    }


    /**
     * 提交订单
     *
     * @param dataBean
     * @param pay_id
     * @param payCode
     * @param num
     */
    public void updateSubmitModel(BoxSubmitModel.DataBean dataBean, String pay_id, String payCode, int num) {
        this.mNum = num;
        this.mBoxSubmitModel = dataBean;
        if (dataBean.need_pay) {
            //余额不够,直接选择支付
            getP().getOrderMsg(dataBean.order_id + "", pay_id, payCode);
        } else {
            //直接跳转到开奖页面
            paySuccess();
        }
    }

    public void showCheckTip() {
        ToastUtil.showLong(this, "获取订单失败,请重试");
    }

    public void showSubmitTip() {
        ToastUtil.showLong(this, "支付失败,没有抵扣您的余额和赠送币,请重试");
    }


    /**
     * 修改开盒纪录
     *
     * @param list
     */
    public void updateList(List<BoxPrizeModel.DataBean.ListBean> list) {
        mBoxHistoryAdapter.updateDate(list);
        if (list.size() >= 100) {
            setCanLoadMore(false);
            View footView = LayoutInflater.from(this).inflate(R.layout.layout_foot_tip, null, false);
            mBoxHistoryAdapter.addFooterView(footView);
        }

    }

    private void setListener() {
        //活动规则
        mTvRule.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BoxDetailActivity.this, RuleActivity.class);
                intent.putExtra("title", "规则说明");
                intent.putExtra("url", ConstantsUrl.domain + ConstantsUrl.OpenBoxRule);
                startActivity(intent);
            }
        });

        mTvOpenBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ShowBoxOpenPopWindow popWindow = new ShowBoxOpenPopWindow(BoxDetailActivity.this, mCurrentListBean);
                popWindow.showPopWindow(view);
                popWindow.setListener(new ShowBoxOpenPopWindow.IShowBoxOpenListener() {
                    @Override
                    public void onClick(OpenBoxWayModel model) {
                        if (UserHolder.getUserInfo(BoxDetailActivity.this) != null) {
                            showLoadingDialog();
                            getP().getBoxCheckOrder(mCurrentListBean.id, model.getNum(), view);
                        } else {
                            startActivity(new Intent(BoxDetailActivity.this, LoginActivity.class));
                        }
                    }
                });
            }
        });

        mBoxAllAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(BoxDetailActivity.this, BoxGoodDetailActivity.class);
                intent.putExtra("BoxModel", mBoxAllAdapter.getData().get(position));
                startActivity(intent);
            }
        });
    }


    /**
     * 试一次
     *
     * @param view
     */
    public void onClickTry(View view) {
        if (WindowUtils.isFastClick()) {
            Intent intent = new Intent(this, UnpackingActivity.class);
            intent.putExtra("BoxListModel", mCurrentListBean);
            startActivity(intent);
        }
    }


    /**
     * 查找所有的
     *
     * @param view
     */
    public void onClickFindAll(View view) {
        if (mCurrentListBean != null) {
            BoxGoodsPopWindow popWindow = new BoxGoodsPopWindow(this, mCurrentListBean, goods_list);
            popWindow.showPopWindow(view);
        }

    }

    /**
     * 分享订单
     *
     * @param view
     */
    public void onClickShareOrder(View view) {
        if (mCurrentListBean != null) {
            Intent intent = new Intent(this, ShareOrderActivity.class);
            intent.putExtra("BoxListModel", mCurrentListBean);
            startActivity(intent);
        }
    }


    public void openQuickPay(BuyMemberShangMengZhiFuRes.DataBean buyMemberShangMengZhiFuData) {
        Intent intent = new Intent(this, QuickPayDetailActivity.class);
        intent.putExtra("buyMemberShangMengZhiFuData", buyMemberShangMengZhiFuData);
        startActivityForResult(intent, 2000);
    }

    public void payFail() {
        ToastUtil.showShort(this, "未完成支付");
    }

    public void paySuccess() {
        if (mBoxSubmitModel != null) {
            if (mNum == 1) {
                Intent intent = new Intent(BoxDetailActivity.this, UnpackingRealActivity.class);
                intent.putExtra("orderId", mBoxSubmitModel.order_id);
                intent.putExtra("BoxListModel",mCurrentListBean);
                intent.putExtra("PayPageWay", OpenBoxFragment.PayCodeFormActivity);
                startActivity(intent);
            } else {
                //跳转到多个箱子
                Intent intent = new Intent(BoxDetailActivity.this, UnpackingFiveActivity.class);
                intent.putExtra("orderId", mBoxSubmitModel.order_id);
                intent.putExtra("BoxListModel",mCurrentListBean);
                intent.putExtra("PayPageWay", OpenBoxFragment.PayCodeFormActivity);
                intent.putExtra("PayCount", mNum);
                startActivity(intent);
            }
        }
    }

    public void toPayByH5(String url) {
        Intent intent = new Intent(this, SimpleWebViewActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("title", "支付");
        startActivity(intent);
    }

    public void toPayByBrowser(String url, String orderId) {
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
        //弹出让用户确定是否支付成功的弹出框
        if (orderId != null) {
            ConfirmPayResultDialog dialog = new ConfirmPayResultDialog(this, orderId, new ConfirmPayResultDialog.CallBack() {
                @Override
                public void callBack(String orderId) {
                    Bus.INSTANCE.send(new RefreshMemberInfoEvent());
                }
            });
            dialog.show();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEventType() == Config.EVENT_BUS_SHOW_ORDER) {
            //再来一发
            if (event.getObjectB().equals(OpenBoxFragment.PayCodeFormActivity)) {
                showLoadingDialog();
                getP().getBoxCheckOrder(mCurrentListBean.id, mNum, mTvOpenBox);
            }
        } else if (event.getEventType() == Config.EVENT_BUS_OPEN_SUCCESS) {
            //开盒成功后重新获取开盒纪录
            getP().getBoxPrizeList(true);
            mBoxGiftsUpView.stop();
            getP().getBoxPrize();

        }else if(event.getEventType()==Config.EVENT_BUS_CLOSE_ACTIVITY){
            finish();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (data != null && data.getExtras() != null && data.getExtras().getBoolean("fail", false)) {
                payFail();
                return;
            }
            if (requestCode == 1000 || requestCode == 2000) {
                if (data != null && data.getExtras() != null && data.getExtras().getBoolean("fail", false)) {

                    payFail();
                    return;
                }
                //翼支付、快捷支付 成功支付
                paySuccess();
                return;
            }


            //对接杉德支付里的银行银联支付=========================================================



            if(requestCode==PAY_CODE) {
                OrderInfo orderInfo = (OrderInfo) data.getSerializableExtra("orderInfo");
                if (orderInfo != null) {
                    if (!TextUtils.isEmpty(orderInfo.getTradeNo())) {
                        startUnionpay(BoxDetailActivity.this, orderInfo.getTradeNo());
                        Bus.INSTANCE.send(new RefreshMemberInfoEvent());
                        return;
                    }
                }
            }
            if(requestCode==UNION_CODE){
                Bundle bundle = data.getExtras();
                if (null == bundle) {
                    return;
                }
                /*
                 * 支付控件返回字符串:
                 * success、fail、cancel 分别代表支付成功，支付失败，支付取消
                 */
                getP().setOut_trade_no(null);
                String result = bundle.getString("pay_result");
                if (result != null) {
                    Intent intent=null;
                    if (result.equalsIgnoreCase("success")) {
                       paySuccess();
                    } else if (result.equalsIgnoreCase("fail")) {
                       payFail();
                    } else if (result.equalsIgnoreCase("cancel")) {
                        ToastUtil.showLong(this,"您已取消支付");
                    }
                }

            }
        }
    }


    @Override
    public SmartRefreshLayout getRefreshView() {
        return findViewById(R.id.id_refreshLayout);
    }

    @Override
    public void onRefresh() {
        getP().getBoxPrizeList(true);
        mBoxGiftsUpView.stop();
        getP().getBoxPrize();
        if (mBoxHistoryAdapter != null) {
            mBoxHistoryAdapter.removeAllFooterView();
        }
    }


    @Override
    public void onLoad() {
        getP().getBoxPrizeList(false);

    }

    public void setCanLoadMore(Boolean canLoadMore) {
        getRefreshView().setEnableLoadMore(canLoadMore);
    }



    //===============================================================对接珊德宝支付======================================
    public void cashierPay(SandPayModel.Data sandPayModel) {
        JSONObject orderJson = new JSONObject();
        try {
            getP().setOut_trade_no(sandPayModel.order.outTradeNo);
            orderJson.put("version", sandPayModel.paycode.version);
            orderJson.put("sign_type", sandPayModel.paycode.signType);
            orderJson.put("mer_no", sandPayModel.paycode.merNo); // 商户编号
            orderJson.put("mer_key", sandPayModel.paycode.merKey); // 商户密钥
            orderJson.put("mer_order_no", sandPayModel.paycode.merOrderNo); // 商户订单号
            orderJson.put("create_time", sandPayModel.paycode.createTime); // 订单创建时间
            orderJson.put("expire_time", sandPayModel.paycode.expireTime); // 订单失效时间
            orderJson.put("order_amt", sandPayModel.paycode.orderAmt); // 订单金额
            orderJson.put("notify_url", sandPayModel.paycode.notifyUrl); // 回调地址
            orderJson.put("return_url", sandPayModel.paycode.returnUrl);//"http://www.baidu.com"); // 支付后返回的商户显示页面
            orderJson.put("create_ip", sandPayModel.paycode.createIp); // 客户端的真实IP
            orderJson.put("goods_name", sandPayModel.paycode.goodsName); // 商品名称
            orderJson.put("store_id", sandPayModel.paycode.storeId); // 门店号
            orderJson.put("product_code", sandPayModel.paycode.productCode); // 支付产品编码
            orderJson.put("clear_cycle", sandPayModel.paycode.clearCycle); // 清算模式
            orderJson.put("accsplit_flag", sandPayModel.paycode.accsplitFlag); // 分账标识 NO无分账，YES有分账
            orderJson.put("sign", sandPayModel.paycode.sign);//签名
            orderJson.put("pay_extra", sandPayModel.paycode.payExtra);
            orderJson.put("jump_scheme","boxcash://boxpay"); // 支付宝返回app所配置的域名
            // orderJson.put("limit_pay", ""); //微信传1屏蔽信用卡，支付宝传5屏蔽部分信用卡以及花呗，支付宝传4屏蔽花呗，支付宝传1屏蔽部分信用卡，银联不支持屏蔽   不参与签名
        } catch (Exception e) {
            e.getStackTrace();
        }
        PayUtil.CashierPay(BoxDetailActivity.this, orderJson.toString());
    }

    public  void  cashierPayH5(SandPayH5Model.Data sandPayH5model){
        getP().setOut_trade_no(sandPayH5model.order.outTradeNo);
        WebViewParameter parameters = new WebViewParameter.WebParameterBuilder()
                .setHtmlUrl(sandPayH5model.paycode.body.credential)
                .setShowProgress(true)
                .setCanHistoryGoBackOrForward(true)
                .setReloadable(true)
                .setShowWebPageTitle(false)
                .setReloadType(ERefreshWebType.ClickRefresh)
                .setCustomTitle("快捷支付")
                .build();
        Intent intent = new Intent(mContext, WebViewActivity.class);
        intent.putExtra("parameters", parameters);
        startActivity(intent);

    }
//    @Override
//    protected void onNewIntent(Intent intent) {
//        super.onNewIntent(intent);
//        Uri uri = intent.getData();
//        if (uri != null) {
//            Intent payIntent=null;
//            String payCode = uri.getQueryParameter("payCode");  // 支付宝支付完后返回app后 所传的code
//            assert payCode != null;
//            if(payCode.equals("2")){
//                paySuccess();
//            }else {
//               payFail();
//            }
//        }
//    }

    /**
     * 银联云闪付
     */
    public static void startUnionpay(Context context, String tradeNo) {
        UPPayAssistEx.startPay(context, null, null, tradeNo, "00");
    }

    public void showPayWay(PayWayModel.Data paWayModel) {
        if (paWayModel.payType.equals("7")) {
            //7表示盲盒订单
            if (paWayModel.payWay == null) {
                return;
            }
            if (paWayModel.payWay.equals("0") ||paWayModel.payWay.equals("1")|| paWayModel.payWay.equals("2")) {
                //表示只有支付宝 和杉德支付宝的时候才调用
                getP().setOut_trade_no(null);
                if (paWayModel.isPaid.equals("1")) {
                    paySuccess();
                } else {
                    payFail();
                }
            }

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (getP().getOut_trade_no() != null&&UserHolder.getUserInfo(this)!=null) {
            getP().getPayWay();
        }
    }
}
